package com.example.weibo_suhuanzhen.fragments;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.weibo_suhuanzhen.LoginEvent;
import com.example.weibo_suhuanzhen.R;
import com.example.weibo_suhuanzhen.UserSession;
import com.example.weibo_suhuanzhen.activities.LoginActivity;
import com.example.weibo_suhuanzhen.bean.WeiboInfo;
import com.example.weibo_suhuanzhen.bean.WeiboInfoPage;
import com.example.weibo_suhuanzhen.adapters.MyAdapter;
import com.example.weibo_suhuanzhen.retrofit.RetrofitManager;
import com.example.weibo_suhuanzhen.retrofit.ShzApi;
import com.example.weibo_suhuanzhen.sharedPreferences.SharedPreferencesManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class HomeFragment extends Fragment {
    private RecyclerView recyclerView;
    private MyAdapter adapter;
    private SharedPreferencesManager preferences;
    private List<WeiboInfo> itemList;
    private SwipeRefreshLayout swipeRefreshLayout;
    private View loadingContainer;
    private View errorContainer;
    private TextView refreshBtn;
    final String TAG="shz_HomeFragment";
    int currentPage = 1;
    int totalPage;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        } // 注册 EventBus
        preferences = SharedPreferencesManager.getInstance(getContext());
        recyclerView = view.findViewById(R.id.recycler_view);
        loadingContainer=view.findViewById(R.id.loading_container);
        errorContainer=view.findViewById(R.id.error_container);
        refreshBtn=view.findViewById(R.id.refresh_button);
        refreshBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getHomePage(1,false);
            }
        });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(linearLayoutManager);

        // Initialize item list
        itemList = new ArrayList<>();
        getHomePage(1,false);

        adapter = new MyAdapter(getContext(), itemList);
        recyclerView.setAdapter(adapter);
        //下拉事件刷新
        swipeRefreshLayout = view.findViewById(R.id.game_smartRefreshLayout);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                currentPage=1;
                refreshData();
            }
        });

        //上拉加载
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                int[] lastVisibleItemPositions = new int[]{linearLayoutManager.findLastVisibleItemPosition()};
                int lastVisibleItemPosition = getLastVisibleItemPosition(lastVisibleItemPositions);
                if (newState ==RecyclerView.SCROLL_STATE_IDLE && lastVisibleItemPosition + 1 ==adapter.getItemCount()) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if(totalPage>currentPage){
                                currentPage++;
                                Toast.makeText(getContext(),"正在刷新第"+currentPage+"页",Toast.LENGTH_SHORT).show();
                                Log.i(TAG, "刷新"+currentPage);
                                getHomePage(currentPage,false);
                            }else Toast.makeText(getContext(),"无更多内容",Toast.LENGTH_SHORT).show();

                        }
                    },500);
                }
            }
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView,dx, dy);
            }
        });
    }

    // 获取倒数第二个可见item的位置
    private int getLastVisibleItemPosition(int[] lastVisibleItemPositions) {
        int max = lastVisibleItemPositions[0];
        for (int i : lastVisibleItemPositions) {
            if (i > max) {
                max = i;
            }
        }
        return max;
    }

    @Override
    public void onResume() {
        super.onResume();
//        if (UserSession.getInstance().isLoggedIn()){
//            itemList.clear();
//            getHomePage(2);
//        }
//        refreshData();
    }

    @SuppressLint("NotifyDataSetChanged")
    public void refreshData(){

        itemList.clear();
        getHomePage(1,true);

        adapter.notifyDataSetChanged();
        swipeRefreshLayout.setRefreshing(false);
    }


    private void getHomePage(int current,boolean refresh){
        if (!preferences.getBoolean("cache",false)){
            loadingContainer.setVisibility(View.VISIBLE);
            errorContainer.setVisibility(View.GONE);
            Handler handler=new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    if (loadingContainer.getVisibility()==View.VISIBLE) {
                        // 如果加载过程中没有出现错误，则继续执行加载数据的操作
                        errorContainer.setVisibility(View.VISIBLE);
                    }
                    loadingContainer.setVisibility(View.GONE);
                }
            }, 5000); // 五秒后发送消息隐藏加载中界面

        }
        String token = preferences.getData("token","");
        ShzApi api = RetrofitManager.getInstance().createApi();
        Call<ShzApi.WeiboInfoResponse> call = api.getHomePage("Bearer " + token,current,10);
        call.enqueue(new Callback<ShzApi.WeiboInfoResponse>() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onResponse(Call<ShzApi.WeiboInfoResponse> call, Response<ShzApi.WeiboInfoResponse> response) {
                if (response.isSuccessful() && response.body() != null && response.body().getCode()!=403) {
                    WeiboInfoPage weiboInfoPage = response.body().getData();
                    totalPage=weiboInfoPage.getPages();
                    itemList.addAll(weiboInfoPage.getRecords());
                    preferences.saveBoolean("cache",true);
                    loadingContainer.setVisibility(View.GONE);
                    errorContainer.setVisibility(View.GONE);
                    adapter.notifyDataSetChanged();
                    if (refresh){
                        Collections.shuffle(itemList);
                    }

                } else if (response.body() != null &&response.body().getCode()==403) {
                    preferences.saveData("token","");
                    getHomePage(current,false);
                }
            }

            @Override
            public void onFailure(Call<ShzApi.WeiboInfoResponse> call, Throwable throwable) {
                errorContainer.setVisibility(View.VISIBLE);
            }
        });

    }

    @Subscribe
    public void onLoginEvent(LoginEvent event) {
            refreshData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this); // 反注册 EventBus
    }


}

